import { getServer } from '/store/mutations'
import { checkAuth, getDomoUser, getUserTopics } from '/store/actions'
import { $event, $utils } from '/utils'
import { GlobalData } from '/store/state'
import { feedApi } from '/api/feed'
import { uploadFile, uploadFileWithUrl } from '/api/file'
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'

Page({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    params: {} as DomoFeed,
    type: '' as string,
    user: {} as DomoUser,
    content: '' as string,
    topics: GlobalData.userTopics.topics,
    localImages: [] as string[],
    netImages: [] as string[],
    netVideo: [] as string[],
    videoPath: '' as string,
    videoContext: '' as any,
    videoFullScreen: false,
    associate: false,
    activeTopics: 0,
    publishing: false,
    videoSize: 0,
    about: '',
    id: '',
    lastPageData: {} as any,
    currencyName: GlobalData.currencyName,
    orderId: 0 as any,
    videoCover: '' as any,
  },
  onLoad({ type = '', about = '', id = '', orderId = 0 }) {
    this.setData({
      isFullScreen: GlobalData.isFullScreen,
      type,
      about,
      id,
      orderId,
    })
    about === 'wendas' ? wx.setNavigationBarTitle({ title: '编辑回答' }) : ''

    const pages = getCurrentPages()
    const lastpage = pages[pages.length - 2]
    if (
      lastpage.route == 'mall/detail/detail' ||
      lastpage.route == 'mall/orderDetail/orderDetail'
    ) {
      wx.setNavigationBarTitle({ title: '商品点评' })
    }
  },
  async doSubmit() {
    if (this.data.publishing) {
      return
    }
    this.handSubmit(this)
  },
  handSubmit: $utils.debounce((that: any) => {
    const {
      data: { type },
    } = that
    that.setData({ publishing: true })
    wx.showLoading({
      title: '处理中',
    })
    switch (type) {
      case 'image':
        that.publishImageFeed()
        break
      case 'video':
        that.publishVideoFeed()
        break
      default:
        that.publishWordFeed()
        break
    }
  }, 200),
  /**
   * 发布图片动态
   */
  async publishImageFeed() {
    const {
      data: { content, localImages, activeTopics, about, lastPageData, id, orderId },
    } = this
    const params: PostFeedPayload =
      about === 'mall_commodities' ||
      about === 'infos' ||
      about === 'knowledge' ||
      about === 'events' ||
      about === 'wendas'
        ? {
            feed_content: content,
            repostable_type: about,
            repostable_id:
              (about === 'knowledge' && id !== '') || (about === 'mall_commodities' && id !== '')
                ? id
                : lastPageData.id,
            images: [] as string[],
          }
        : {
            feed_content: content,
            topics: activeTopics ? [activeTopics] : [],
            theme: about === 'theme' ? lastPageData.id : null,
            images: [] as string[],
          }
    try {
      // eslint-disable-next-line no-case-declarations
      const imgDatas = await Promise.all(
        localImages.map(async (i: string) => {
          return await uploadFileWithUrl(i)
        }),
      )
      params.images = imgDatas.map((i: any) => {
        return i.node
      })
      about === 'mall_commodities' && orderId > 0 ? (params.mall_order_id = orderId) : ''
      this.publishFeed(params)
    } catch (error) {
      this.handlePushlishFail(error)
    }
  },

  /** 发布失败 */
  handlePushlishFail(error: any) {
    this.setData({ publishing: false })
    wx.showToast({
      title: `${getMessage(error.data).getMessage() || '发布失败'}`,
      icon: 'none',
    })
    wx.hideLoading()
  },
  /**
   *  发布文字动态
   */
  async publishWordFeed() {
    const {
      data: { content, activeTopics, about, lastPageData, id, orderId },
    } = this
    let params: PostFeedPayload

    if (about === 'mall_commodities' && content.length < 10) {
      wx.showToast({
        title: '点评文字不低于10个字',
        icon: 'none',
      })

      return
    }
    params = params =
      about === 'mall_commodities' ||
      about === 'infos' ||
      about === 'knowledge' ||
      about === 'events' ||
      about === 'wendas'
        ? {
            feed_content: content,
            repostable_type: about,
            repostable_id:
              (about === 'knowledge' && id !== '') || (about === 'mall_commodities' && id !== '')
                ? id
                : lastPageData.id,
          }
        : {
            feed_content: content,
            topics: activeTopics ? [activeTopics] : [],
            theme: about === 'theme' ? lastPageData.id : null,
          }
    about === 'mall_commodities' && orderId > 0 ? (params.mall_order_id = orderId) : ''
    this.publishFeed(params)
  },

  /**
   * 发布视频动态
   */
  async publishVideoFeed() {
    const {
      data: {
        content,
        videoSize,
        videoPath,
        videoCover,
        activeTopics,
        about,
        lastPageData,
        id,
        orderId,
      },
    } = this

    if (!videoCover || !videoPath) {
      this.publishWordFeed()
      return
    }

    let params: PostFeedPayload
    // eslint-disable-next-line no-case-declarations
    try {
      const cover = await uploadFile(videoCover)
      await uploadFile(videoPath, videoSize).then(async (data) => {
        params = params =
          about === 'mall_commodities' ||
          about === 'infos' ||
          about === 'knowledge' ||
          about === 'events' ||
          about === 'wendas'
            ? {
                video: {
                  resource: data,
                  cover,
                },
                feed_content: content,
                repostable_type: about,
                repostable_id:
                  (about === 'knowledge' && id !== '') ||
                  (about === 'mall_commodities' && id !== '')
                    ? id
                    : lastPageData.id,
              }
            : {
                video: {
                  resource: data,
                  cover,
                },
                feed_content: content,
                topics: activeTopics ? [activeTopics] : [],
                theme: about === 'theme' ? lastPageData.id : null,
              }
        about === 'mall_commodities' && orderId > 0 ? (params.mall_order_id = orderId) : ''
        this.publishFeed(params)
      })
    } catch (error) {
      this.handlePushlishFail(error)
    }
  },

  async publishFeed(params: PostFeedPayload) {
    const {
      data: { about, id, content },
    } = this
    if (content.length > 800) {
      wx.showToast({
        title: '最多发布800个字节',
        icon: 'none',
      })

      return
    }
    feedApi
      .postFeed(params)
      .then(() => {
        wx.showToast({
          title: '发布成功',
        })
        /** 发布成功触发事件 */
        $event.emit(`after:${about}`, id)
        setTimeout(() => {
          wx.navigateBack({ delta: 1 })
          $event.emit('after:publishdynamic')
        }, 1000)
      })
      .catch((error) => {
        this.handlePushlishFail(error)
      })
  },
  contentChange(e: any) {
    const {
      detail: { value },
    } = e
    this.setData({
      content: value,
    })
  },
  async onShow() {
    $event.on('after:login', this, async () => {
      this.getUserInfo()
    })
    this.setData({
      currencyName: GlobalData.currencyName,
    })
    if (!GlobalData.access.ugc) {
      wx.switchTab({
        url: '/pages/feed/list/list',
      })
    }
    await checkAuth()
    this.getUserInfo()
    this.data.about != '' ? this.getLastPageData() : ''
  },
  getLastPageData() {
    const pages = getCurrentPages()
    const lastPage = pages[pages.length - 2]
    const lastPageData = lastPage.data[`${this.data.about}`]
    this.setData({
      lastPageData,
      activeTopics: this.data.about === 'topic' ? lastPageData.id : 0,
    })
  },
  async loadTopics() {
    wx.showNavigationBarLoading()
    const {
      data: {
        user: { id },
      },
    } = this
    this.setData(
      {
        associate: true,
        topics: await getUserTopics({ for_user: id, limit: 100 }),
      },
      () => {
        wx.hideNavigationBarLoading()
      },
    )
  },
  /** 选中或取消选中关联圈子 */
  activeOrNot(e: any) {
    const {
      data: { activeTopics },
    } = this
    const {
      currentTarget: {
        dataset: { topicid },
      },
    } = e

    this.setData({
      activeTopics: topicid === activeTopics ? 0 : topicid,
    })
  },
  /** 选中图片 */
  handleImage() {
    // const fs = wx.getFileSystemManager()
    if (this.data.localImages.length === 9) {
      wx.showToast({
        title: '你只能最多选择9张照片',
        icon: 'none',
      })
      return
    }

    wx.chooseImage({
      count: 9,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: ({ tempFilePaths }) => {
        const images = this.data.localImages.concat(tempFilePaths)
        if (images.length > 9) {
          wx.showToast({
            title: '你只能最多选择9张照片',
            icon: 'none',
          })
        }
        const localImages = images.length > 9 ? images.splice(0, 9) : images
        this.setData({ localImages })
      },
    })
  },
  /** 取消选择图片 */
  deletImg(e: any) {
    console.log(e)

    const index = e.currentTarget.dataset.index
    const img = this.data.localImages
    img.splice(index, 1)
    this.setData({
      localImages: img,
    })
  },
  /** 预览图片 */
  showImages(e: any) {
    const {
      target: {
        dataset: { index },
      },
    } = e
    wx.previewImage({
      urls: this.data.localImages,
      current: this.data.localImages[index],
    })
  },
  /** 视频预览全屏事件捕获 */
  fullscreenchange({ detail: { fullScreen } }: { detail: any; fullScreen: boolean }) {
    this.setData({
      videoFullScreen: fullScreen,
    })
  },
  /** 选择视频事件 */
  handleVideo() {
    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    // @ts-ignore
    wx.chooseMedia({
      count: 1,
      mediaType: ['video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: (res: any) => {
        if (res.tempFiles[0].size > 25000000) {
          wx.showToast({
            title: '选择的视频文件过大',
            icon: 'none',
          })

          return
        }
        this.setData({
          videoContext: wx.createVideoContext('chosen-video', this),
          videoPath: res.tempFiles[0].tempFilePath,
          videoSize: res.tempFiles[0].size,
          videoCover: res.tempFiles[0].thumbTempFilePath,
        })
      },
    })
  },
  /**
   * 获取用户信息及用户圈子
   */
  async getUserInfo() {
    await getDomoUser()
    const server = getServer()
    const user = wx.getStorageSync(`${server}/logged`).data || {}

    this.setData({
      user,
    })
  },
  /** 发送动态 */
})
